import cryptoJS from 'crypto-js';
import axios from 'axios';
import qs from 'qs';
interface Base {
    'us-phonetic': string;
    'uk-phonetic': string;
    explains: string[];
}
interface ResData {
    basic: Base,
    web: { key: string, value: string }[],
    translation: string[]
}
function truncate(q: string): string {
    let len = q.length;

    if (len <= 20) {
        return q;
    }
    return q.substring(0, 10) + len + q.substring(len - 10, len);
}

export async function translate(query: string, appKey: string, appSecret: string): Promise<ResData> {

    // let appKey = '7ab91265f83e07b5';
    // let key = 'FRAH9Om02OTPh8bTkgALs4PceCNej19g';
    let salt = new Date().getTime();
    let curtime = Math.round(new Date().getTime() / 1000);
    // 多个query可以用\n连接  如 query='apple\norange\nbanana\npear'
    let from = 'AUTO';
    let to = 'AUTO';
    let str1 = appKey + truncate(query) + salt + curtime + appSecret;

    // eslint-disable-next-line new-cap
    let sign = cryptoJS.SHA256(str1).toString(cryptoJS.enc.Hex);
    const res = await axios.post(
        'http://openapi.youdao.com/api',
        qs.stringify({
            q: query,
            appKey,
            salt,
            from,
            to,
            sign,
            signType: 'v3',
            curtime
        })
    );

    return res.data;
}
export function letterToLowerCase(arr: string[]): string {
    return arr.map(function (val, index, arr) {
        return arr[index].charAt(0).toLowerCase() + '' + arr[index].slice(1, arr.length - 1);
    }).join('');
}
export function changeWord(text: string): string {
    if (!text.includes(' ') && text.match(/[A-Z]/)) {
        const str = text.replace(/([A-Z])/g, ' $1');
        let value = str.substring(0, 1).toUpperCase() + str.substring(1);

        return value;
    }
    return text;
}
